﻿using Microsoft.Practices.Prism.StoreApps;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Reflection;
using System.Globalization;
using JV.Com.ViewModels.Wrapper;
using JV.Com.ViewModels;
using JV.Com.Internals;
using System.Threading.Tasks;
using System.Threading;
using Windows.UI.Xaml.Media.Animation;
using Microsoft.Practices.Prism.StoreApps.Interfaces;

// Pour en savoir plus sur le modèle d'élément Page vierge, consultez la page http://go.microsoft.com/fwlink/?LinkId=234238

namespace JV.Com.Views
{
    /// <summary>
    /// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
    /// </summary>
    public sealed partial class NewsListPage : PageBase
    {
        private bool m_firstFlipSelection;
        public NewsListPage()
        {
            m_firstFlipSelection = true;
            this.InitializeComponent();
        }
        
        private async void News_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (m_firstFlipSelection)
            {
                m_firstFlipSelection = false;
            }
            else
            {
                if (e.AddedItems.Count == 1)
                {
                    var dispatcher = Window.Current.Dispatcher;
                    var wrapper = (NewsWrapper)e.AddedItems[0];
                    await wrapper.LoadContentAsync();
                    var index = ((FlipView)sender).Items.IndexOf(wrapper);
                    ScrollToIndex(index);
                }
            }
        }

        private void ScrollToIndex(int index)
        {
            var destinationZoneMin = index * 100;
            var destinationZoneMax = destinationZoneMin + 100;
            var height = NewsListScroll.ActualHeight;
            var offset = NewsListScroll.VerticalOffset;
            var currentZoneMin = offset;
            var currentZoneMax = offset + height;
            if (currentZoneMin > destinationZoneMin)
            {
                NewsListScroll.ChangeView(null, destinationZoneMin, null);
            }
            else if (currentZoneMax < destinationZoneMax)
            {
                NewsListScroll.ChangeView(null, destinationZoneMax - height, null);
            }
        }
    }
}
